package com.prodavalnik.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.prodavalnik.model.Category;
import com.prodavalnik.model.DataBaseController;
import com.prodavalnik.model.Product;

/**
 * Servlet implementation class NewADServlet
 */
@WebServlet("/NewADServlet")
public class NewADServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public NewADServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	
	public String storeLocation(String value){
	
		return value.substring(value.indexOf("StoreLocation=")+13,value.indexOf(".tmp")+4);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
	
			List<FileItem> items =  (new ServletFileUpload(new DiskFileItemFactory())).parseRequest(request);
			Iterator<FileItem> iter = items.iterator();
			List<File>listOfImages = new ArrayList<File>();
			String productName = null,productDescription = null;
			BigDecimal productPrice = null;
			String category=null;
			while(iter.hasNext()){
				 FileItem item = iter.next();
				if(item.isFormField()){
					String name = item.getFieldName();
					byte[] nameOfValue = item.get();
					String value = new String(nameOfValue);
					
					if(name.equals("name-input"))
						productName = value;
					else if(name.equals("price-input")){
						productPrice = new BigDecimal(value);
					}
					else if(name.equals("desc-input"))
						productDescription = value;
					
					else if(name.equals("category"))
						category = value;

				}
				else{
	                byte[] image = item.get();
	                java.util.Date date1 = new java.util.Date();      
	                File f = new File(DataBaseController.PATH_TO_DIR_WHERE_IMAGES_ARE_SAVED +"\\"+date1.getTime()+".jpg");
	                f.createNewFile();
	                FileOutputStream fos = new FileOutputStream(f);
	                fos.write(image);
	                fos.close();
	                listOfImages.add(f);
				}
			}
			if(productName == null || productName.isEmpty()){
				PrintWriter categoryErrorWriter= response.getWriter();
				categoryErrorWriter.println("<h1>You haven't chosen a product name </h1>");
				categoryErrorWriter.println("<a href='profile-settings.html'>Back to previous page</a>" );
				return;
			}
		
			if(category == null){
				PrintWriter categoryErrorWriter= response.getWriter();
				categoryErrorWriter.println("<h1>You haven't chosen a category </h1>");
				categoryErrorWriter.println("<a href='profile-settings.html'>Back to previous page</a>" );
				return;
			}
			java.util.Date date = new java.util.Date();
			Category c = (Category) DataBaseController.findCategoryByName(category);
			Product p = new Product(c.getId(),productName,productDescription,productPrice,date,listOfImages);
			DataBaseController.addProductToDB(p);
			response.sendRedirect("http://localhost:8080/Prodavalnik/profile-settings.html");
		} 
		catch(NumberFormatException e){
			PrintWriter pw = response.getWriter();
			pw.println("<h1>You have input invalid price (only digits)</h1>");
			pw.println("<a href='profile-settings.html'>Back to previous page</a>" );
		}
		
		catch (FileUploadException e) {
			e.printStackTrace();
		}
		
	}

}